package com.richie696.catalina;

import org.apache.commons.lang3.ArrayUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ApplicationHttpResponse implements HttpServletResponse {

    private final OutputStream outputStream;
    private final PrintWriter printWriter;
    private final String base;

    public ApplicationHttpResponse(OutputStream outputStream, String base) {
        this.outputStream = outputStream;
        this.printWriter = new PrintWriter(outputStream);
        this.base = base;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return outputStream;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return printWriter;
    }

    @Override
    public void sendRedirect(String location) throws IOException {
        InputStream inputStream = Files.newInputStream(Paths.get(base + location));

        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        byte[] bytes = new byte[count];
        int read;
        do {
            read = inputStream.read(bytes);
        } while (read < count);
        String header = HttpProtocolUtil.getHttpHeader200(bytes.length);
        bytes = ArrayUtils.addAll(header.getBytes(), bytes);
        outputStream.write(bytes);
        outputStream.flush();
    }

}
